package org.my.stock.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MyDaongFanHttp {

    // 从HTTP头获取编码
    private static Charset getEncodingFromResponse(HttpResponse response) {
        try {
            String contentType = response.getEntity().getContentType().getValue();
            String[] values = contentType.split(";");
            for (String value : values) {
                value = value.trim();
                if (value.toLowerCase().startsWith("charset=")) {
                    String charset = value.substring("charset=".length());
                    return Charset.forName(charset);
                }
            }
        } catch (Exception ignored) {}
        return null;
    }

    // 从HTML meta标签解析编码
    private static Charset parseEncodingFromHtml(String html) {
        String lowerHtml = html.toLowerCase();
        int metaPos = lowerHtml.indexOf("<meta");
        while (metaPos != -1) {
            int endPos = lowerHtml.indexOf(">", metaPos);
            if (endPos == -1) break;

            String metaTag = html.substring(metaPos, endPos);
            if (metaTag.contains("charset")) {
                int charsetPos = metaTag.indexOf("charset=");
                if (charsetPos != -1) {
                    charsetPos += "charset=".length();
                    int end = metaTag.indexOf("\"", charsetPos);
                    if (end == -1) end = metaTag.indexOf("'", charsetPos);
                    if (end == -1) end = metaTag.indexOf(" ", charsetPos);
                    if (end == -1) end = metaTag.length();

                    String charset = metaTag.substring(charsetPos, end)
                            .replace("\"", "").replace("'", "").trim();
                    try {
                        return Charset.forName(charset);
                    } catch (Exception e) {
                        System.err.println("不支持的编码: " + charset);
                    }
                }
            }
            metaPos = lowerHtml.indexOf("<meta", endPos);
        }
        return null;
    }

    public static void getData(String url) {
        HttpClient httpClient = HttpClients.createDefault();

        try {
            // 1. 创建 GET 请求
            HttpGet request = new HttpGet(url);

            // 2. 设置请求头（防止被服务器拒绝）
            request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
            request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            request.setHeader("Accept-Encoding", "gzip, deflate, br");
            request.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
            request.setHeader("Cache-Control", "max-age=0");
            request.setHeader("Connection", "keep-alive");
            //request.setHeader("Cookie", "em_hq_fls=js; intellpositionL=1140px; em-quote-version=topspeed; intellpositionT=1298px; qgqp_b_id=e04e31a1e6446068e54e0f7808401919; sid=142772185; mtp=1; ct=oFv-pht6ZiYeFSXV2tPdRfkJ0x6ZftJa4X2TKji2eXO0Pl_YBbWxGBEwUTJ4z6N0GPPyYYrAizsB50OwF5PQc3x4HESZOAriGonI9ewh-RikgY0SEGHZcdA5RKg5RB4dPVIr3TCQLKkZkYOXQKFQElZVysNazqJ5O7csdsQO8U8; ut=FobyicMgeV5FJnFT189SwH2JOfiEw7mPz0LG7-oku6sFYOCxdbsEi2cnDTMMTwLC08VTgq_y28iF-S7gffFe0HKuLD1gS302VWRzT3pl7pFn5lPVWP0FGEkMzX3xkH4zZ26gwPXYW-E0EBZ8yNwMjA61nTdT3wPUm2MO4K_-pv5FU7C4OKwrxdk0UuppgrEnJEgArYW9ONwiZM25_K7mvoROgdu_rvCGeunwxnPYxpGqdl5zugvVg1iYtj7NhgcPysSINh74Fg1SOz2r1EMofNQ2h17qfzYUEa1h5_9kJkiB1FoE_P6A7kqYkMsr92-xF4fQoC_luUS273FRQNpqdmsbdOgZn9GV; pi=5274385825271944%3Bc5274385825271944%3B%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90%3BdCmpCdx6Fv0K9ySmGo1L60bQl9guPYNF9kW50ggeyA%2BOOeqCGeepIZPP0w088pbSCmH3QEBcYqyucZR9kKKJ4yNWHFBnnJznMgN%2F0PAMxp8Q%2FuJWZ89w97SHWrysOsb%2B93O45rM%2BhQroFhMO0X604MpHaHC%2F9yVsQmkbCVr5W1pviVaJGTOj%2FDWWzVmDAqUqGJzUNqW2%3BYeT6DxMds0uwdT3PftF0xut%2B1faguRkAY5Rpcphp0hhNyyGaYsTQbiMZEJxNWp7SrYuMigne0BGrZhWVS5SuyPZkN9SQHEd8yzBJUAbFcxV2So8rHP9l%2FY1Cf50pniZsBXw%2Bk0GvzjRxxPfbt9j1Vj8dTOWabw%3D%3D; vtpst=%7C; uidal=5274385825271944%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90; emshistory=%5B%22undefined%22%2C%22%E6%BD%9E%E5%AE%89%E7%8E%AF%E8%83%BD%22%5D; fullscreengg=1; fullscreengg2=1; st_si=91941832585460; st_asi=delete; HAList=ty-90-BK0477-%u917F%u9152%u884C%u4E1A%2Cty-90-BK0729-%u8239%u8236%u5236%u9020%2Cty-90-BK1063-%u91CD%u7EC4%u86CB%u767D%2Cty-0-000938-%u7D2B%u5149%u80A1%u4EFD%2Cty-1-688981-%u4E2D%u82AF%u56FD%u9645%2Cty-90-BK0739-%u5DE5%u7A0B%u673A%u68B0%2Cty-90-BK1017-%u91C7%u6398%u884C%u4E1A%2Cty-1-603198-%u8FCE%u9A7E%u8D21%u9152%2Cty-0-002342-%u5DE8%u529B%u7D22%u5177%2Cty-0-002204-%u5927%u8FDE%u91CD%u5DE5; st_pvi=18633756697256; st_sp=2021-05-13%2015%3A20%3A17; st_inirUrl=https%3A%2F%2Fcn.bing.com%2F; st_sn=29; st_psi=20250406215330169-113200301353-5631822578");
            request.setHeader("Host", "push2.eastmoney.com");
            request.setHeader("Referer", "https://quote.eastmoney.com/sz000001.html");
            request.setHeader("Host", "push2his.eastmoney.com");

            // 3. 执行请求并获取响应
            HttpResponse response = httpClient.execute(request);
            response.setHeader("Content-Encoding", "br");
            response.setHeader("Content-Type", "application/javascript; charset=UTF-8");

            // 4. 检查状态码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("HTTP 状态码: " + statusCode);

            // 5. 读取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {

                //byte[] rawBytes = EntityUtils.toByteArray(entity);
                //Files.write(Paths.get("/Users/chenfei/temp/my.bin"), rawBytes);

                // 方案1：优先使用响应头中的编码
                //Charset encoding = getEncodingFromResponse(response);

                // 方案2：如果响应头未指定，尝试从HTML meta标签解析
//                if (encoding == null) {
//                    String tempContent = EntityUtils.toString(entity, "UTF-8"); // 临时用UTF-8读取
//                    encoding = parseEncodingFromHtml(tempContent);
//                }

                // 最终使用正确编码读取内容
                //String content = EntityUtils.toString(entity, encoding != null ? encoding : Charset.defaultCharset());
                String content = EntityUtils.toString(entity, "UTF-8");
                System.out.println("正确解码内容:\n" + content);
            }

        } catch (Exception e) {
            System.err.println("请求失败: " + e.getMessage());
        } finally {
            // 6. 释放连接（重要！）
            httpClient.getConnectionManager().shutdown();
        }

    }

    public static void getData_1(String url) {
        HttpClient httpClient = HttpClients.createDefault();

        try {
            // 1. 创建 GET 请求
            HttpGet request = new HttpGet(url);

            // 2. 设置请求头（防止被服务器拒绝）
            request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
            request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
            request.setHeader("Accept-Encoding", "gzip, deflate, br");
            request.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
            request.setHeader("Cache-Control", "max-age=0");
            request.setHeader("Connection", "keep-alive");
            request.setHeader("Cookie", "em_hq_fls=js; intellpositionL=1140px; em-quote-version=topspeed; intellpositionT=1298px; qgqp_b_id=e04e31a1e6446068e54e0f7808401919; sid=142772185; mtp=1; ct=oFv-pht6ZiYeFSXV2tPdRfkJ0x6ZftJa4X2TKji2eXO0Pl_YBbWxGBEwUTJ4z6N0GPPyYYrAizsB50OwF5PQc3x4HESZOAriGonI9ewh-RikgY0SEGHZcdA5RKg5RB4dPVIr3TCQLKkZkYOXQKFQElZVysNazqJ5O7csdsQO8U8; ut=FobyicMgeV5FJnFT189SwH2JOfiEw7mPz0LG7-oku6sFYOCxdbsEi2cnDTMMTwLC08VTgq_y28iF-S7gffFe0HKuLD1gS302VWRzT3pl7pFn5lPVWP0FGEkMzX3xkH4zZ26gwPXYW-E0EBZ8yNwMjA61nTdT3wPUm2MO4K_-pv5FU7C4OKwrxdk0UuppgrEnJEgArYW9ONwiZM25_K7mvoROgdu_rvCGeunwxnPYxpGqdl5zugvVg1iYtj7NhgcPysSINh74Fg1SOz2r1EMofNQ2h17qfzYUEa1h5_9kJkiB1FoE_P6A7kqYkMsr92-xF4fQoC_luUS273FRQNpqdmsbdOgZn9GV; pi=5274385825271944%3Bc5274385825271944%3B%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90%3BdCmpCdx6Fv0K9ySmGo1L60bQl9guPYNF9kW50ggeyA%2BOOeqCGeepIZPP0w088pbSCmH3QEBcYqyucZR9kKKJ4yNWHFBnnJznMgN%2F0PAMxp8Q%2FuJWZ89w97SHWrysOsb%2B93O45rM%2BhQroFhMO0X604MpHaHC%2F9yVsQmkbCVr5W1pviVaJGTOj%2FDWWzVmDAqUqGJzUNqW2%3BYeT6DxMds0uwdT3PftF0xut%2B1faguRkAY5Rpcphp0hhNyyGaYsTQbiMZEJxNWp7SrYuMigne0BGrZhWVS5SuyPZkN9SQHEd8yzBJUAbFcxV2So8rHP9l%2FY1Cf50pniZsBXw%2Bk0GvzjRxxPfbt9j1Vj8dTOWabw%3D%3D; vtpst=%7C; uidal=5274385825271944%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90; xsb_history=872107%7C%u660A%u534E%u80A1%u4EFD; emshistory=%5B%22%E5%9B%BA%E6%80%81%E7%94%B5%E6%B1%A0%22%2C%22%E8%83%BD%E6%BA%90%E9%87%91%E5%B1%9E%22%2C%22%E6%99%B6%E6%96%B9%E7%A7%91%E6%8A%80%22%2C%22%E5%B9%B3%E5%AE%89%E9%93%B6%E8%A1%8C%22%2C%22%E5%8D%9A%E8%BF%81%E6%96%B0%E6%9D%90%22%2C%22%E4%B8%87%E6%B6%A6%E6%96%B0%E8%83%BD%22%2C%22%E4%BC%9F%E5%88%9B%E7%94%B5%E6%B0%94%22%2C%22%E6%B4%9B%E9%98%B3%E9%92%BC%E4%B8%9A%22%2C%22%E5%B8%B8%E5%AE%9D%E8%82%A1%E4%BB%BD%22%2C%22%E8%BF%8E%E9%A9%BE%E8%B4%A1%E9%85%92%22%5D; fullscreengg=1; fullscreengg2=1; st_si=91873668993326; HAList=ty-0-000001-%u5E73%u5B89%u94F6%u884C%2Cty-1-603198-%u8FCE%u9A7E%u8D21%u9152%2Cty-1-600875-%u4E1C%u65B9%u7535%u6C14%2Cty-90-BK1034-%u7535%u6E90%u8BBE%u5907%2Cty-1-600549-%u53A6%u95E8%u94A8%u4E1A%2Cty-0-301536-%u661F%u5BB8%u79D1%u6280%2Cty-1-688620-%u5B89%u51EF%u5FAE%2Cty-1-605376-%u535A%u8FC1%u65B0%u6750%2Cty-1-601699-%u6F5E%u5B89%u73AF%u80FD%2Cty-1-600809-%u5C71%u897F%u6C7E%u9152; st_pvi=18633756697256; st_sp=2021-05-13%2015%3A20%3A17; st_inirUrl=https%3A%2F%2Fcn.bing.com%2F; st_sn=23; st_psi=20250527190633421-113200354966-4719255991; st_asi=20250527190633421-113200354966-4719255991-web.xgnhqdy.rk-3");
            //request.setHeader("Cookie", "em_hq_fls=js; intellpositionL=1140px; em-quote-version=topspeed; intellpositionT=1298px; qgqp_b_id=e04e31a1e6446068e54e0f7808401919; sid=142772185; mtp=1; ct=oFv-pht6ZiYeFSXV2tPdRfkJ0x6ZftJa4X2TKji2eXO0Pl_YBbWxGBEwUTJ4z6N0GPPyYYrAizsB50OwF5PQc3x4HESZOAriGonI9ewh-RikgY0SEGHZcdA5RKg5RB4dPVIr3TCQLKkZkYOXQKFQElZVysNazqJ5O7csdsQO8U8; ut=FobyicMgeV5FJnFT189SwH2JOfiEw7mPz0LG7-oku6sFYOCxdbsEi2cnDTMMTwLC08VTgq_y28iF-S7gffFe0HKuLD1gS302VWRzT3pl7pFn5lPVWP0FGEkMzX3xkH4zZ26gwPXYW-E0EBZ8yNwMjA61nTdT3wPUm2MO4K_-pv5FU7C4OKwrxdk0UuppgrEnJEgArYW9ONwiZM25_K7mvoROgdu_rvCGeunwxnPYxpGqdl5zugvVg1iYtj7NhgcPysSINh74Fg1SOz2r1EMofNQ2h17qfzYUEa1h5_9kJkiB1FoE_P6A7kqYkMsr92-xF4fQoC_luUS273FRQNpqdmsbdOgZn9GV; pi=5274385825271944%3Bc5274385825271944%3B%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90%3BdCmpCdx6Fv0K9ySmGo1L60bQl9guPYNF9kW50ggeyA%2BOOeqCGeepIZPP0w088pbSCmH3QEBcYqyucZR9kKKJ4yNWHFBnnJznMgN%2F0PAMxp8Q%2FuJWZ89w97SHWrysOsb%2B93O45rM%2BhQroFhMO0X604MpHaHC%2F9yVsQmkbCVr5W1pviVaJGTOj%2FDWWzVmDAqUqGJzUNqW2%3BYeT6DxMds0uwdT3PftF0xut%2B1faguRkAY5Rpcphp0hhNyyGaYsTQbiMZEJxNWp7SrYuMigne0BGrZhWVS5SuyPZkN9SQHEd8yzBJUAbFcxV2So8rHP9l%2FY1Cf50pniZsBXw%2Bk0GvzjRxxPfbt9j1Vj8dTOWabw%3D%3D; vtpst=%7C; uidal=5274385825271944%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90; emshistory=%5B%22undefined%22%2C%22%E6%BD%9E%E5%AE%89%E7%8E%AF%E8%83%BD%22%5D; fullscreengg=1; fullscreengg2=1; st_si=91941832585460; st_asi=delete; HAList=ty-90-BK0477-%u917F%u9152%u884C%u4E1A%2Cty-90-BK0729-%u8239%u8236%u5236%u9020%2Cty-90-BK1063-%u91CD%u7EC4%u86CB%u767D%2Cty-0-000938-%u7D2B%u5149%u80A1%u4EFD%2Cty-1-688981-%u4E2D%u82AF%u56FD%u9645%2Cty-90-BK0739-%u5DE5%u7A0B%u673A%u68B0%2Cty-90-BK1017-%u91C7%u6398%u884C%u4E1A%2Cty-1-603198-%u8FCE%u9A7E%u8D21%u9152%2Cty-0-002342-%u5DE8%u529B%u7D22%u5177%2Cty-0-002204-%u5927%u8FDE%u91CD%u5DE5; st_pvi=18633756697256; st_sp=2021-05-13%2015%3A20%3A17; st_inirUrl=https%3A%2F%2Fcn.bing.com%2F; st_sn=29; st_psi=20250406215330169-113200301353-5631822578");
            request.setHeader("Host", "push2.eastmoney.com");
            request.setHeader("Referer", "https://quote.eastmoney.com/concept/sz000001.html");
            request.setHeader("Host", "push2his.eastmoney.com");

            // 3. 执行请求并获取响应
            HttpResponse response = httpClient.execute(request);
            response.setHeader("Content-Encoding", "br");
            response.setHeader("Content-Type", "application/javascript; charset=UTF-8");

            // 4. 检查状态码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("HTTP 状态码: " + statusCode);

            // 5. 读取响应内容
            HttpEntity entity = response.getEntity();
            if (entity != null) {

                //byte[] rawBytes = EntityUtils.toByteArray(entity);
                //Files.write(Paths.get("/Users/chenfei/temp/my.bin"), rawBytes);

                // 方案1：优先使用响应头中的编码
                //Charset encoding = getEncodingFromResponse(response);

                // 方案2：如果响应头未指定，尝试从HTML meta标签解析
//                if (encoding == null) {
//                    String tempContent = EntityUtils.toString(entity, "UTF-8"); // 临时用UTF-8读取
//                    encoding = parseEncodingFromHtml(tempContent);
//                }

                // 最终使用正确编码读取内容
                //String content = EntityUtils.toString(entity, encoding != null ? encoding : Charset.defaultCharset());
                String content = EntityUtils.toString(entity, "UTF-8");
                System.out.println("正确解码内容:\n" + content);
            }

        } catch (Exception e) {
            System.err.println("请求失败: " + e.getMessage());
        } finally {
            // 6. 释放连接（重要！）
            httpClient.getConnectionManager().shutdown();
        }

    }
}
